package com.bwie.service;

import com.bwie.bo.SpuBo;
import com.bwie.client.*;
import com.bwie.pojo.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class GoodsService {
    @Autowired
    private BrandClient brandClient;

    @Autowired
    SkuClient skuClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private SpecClient specClient;


    @Autowired
    private GoodsClient goodsClient;


    private static final ObjectMapper MAPPER =   new ObjectMapper();

    /**
     * 数据的封装
     * @param spuBo
     * @return
     */
    public Goods buildGoods(SpuBo spuBo) throws Exception {
        System.out.println("运行的spuId:"+spuBo.getId());
        //创建goods对象
        Goods goods = new Goods();


        //查询商品分类名称
        List<String> categoryNameList = categoryClient.queryNamesByIds(Arrays.asList(spuBo.getCid1(), spuBo.getCid2(), spuBo.getCid3()));

        //查询spu下的所有sku
        List<Sku> skus = skuClient.findSkuList(spuBo.getId());

        //查询品牌
        Brand brand = brandClient.queryBrandNameByBrandId(spuBo.getBrandId());



        //把价格 list集合
        List<Long> prices = new ArrayList<Long>();
        //用来存放sku集合的map数据
        List<Map<String,Object>> skuMapList = new ArrayList<>();

        //遍历skus数据，获取价格集合
        if (!CollectionUtils.isEmpty(skus)){
            skus.forEach(sku -> {
                prices.add(Long.valueOf(sku.getPrice())); //把价格进行赋值

                //封装sku集合数据到 map中
                Map<String,Object> skuMap = new HashMap<String,Object>();
                skuMap.put("id",sku.getId());
                skuMap.put("title",sku.getTitle());
                skuMap.put("price",sku.getPrice());
                if (!StringUtils.isEmpty(sku.getImages())){
                    String imagesOne = sku.getImages().split(",")[0];
                    skuMap.put("image",imagesOne );
                }else {
                    skuMap.put("image","" );
                }
                skuMapList.add(skuMap);

            });
        }


        /**********************************************处理规格参数**********************************************************************/

        //查询所有符合条件的规格参数  规格的 key
        List<SpecParam> params = specClient.findSpecParamList(null, spuBo.getCid3(), null, true);


        //查询spuDetail 获取规格参数值  value
        SpuDetail spuDetail = goodsClient.getSpuDetail(spuBo.getId());
        //获取通用的规格参数
        String genericSpec = spuDetail.getGenericSpec();
        //key value  一个 hashMap的结构
        Map<Long,Object> genericSpecMap = MAPPER.readValue(genericSpec, new TypeReference<Map<Long, Object>>() {
        });

        //获取特殊的规格参数
        String specialSpec = spuDetail.getSpecialSpec();
        Map<Long, List<Object>> specialSpecMap = MAPPER.readValue(specialSpec, new TypeReference<Map<Long, List<Object>>>() {
        });

        //定义Map接收 {规格参数名，规格参数值}
        Map<String,Object> paramMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(params)) {
            for (SpecParam param : params) {
                String value = "";
                //判断是否通用的规格参数
                if (param.getGeneric()) {
                    value = genericSpecMap.get(param.getId()).toString();

                    //判断是否是数值类型
                    if (param.getNumeric()) {
                        //如果是数值类型得判断数值类型应该在哪个区间？
                        value = choseSegment(value, param);
                    }
                    //把参数名和值放到结果集中
                    paramMap.put(param.getName(), value);
                } else {
                    paramMap.put(param.getName(), specialSpecMap.get(param.getId()));
                }


            }
        }

        /********************************************************************************************************************/

        //设置参数
        goods.setId(spuBo.getId());
        goods.setCid1(spuBo.getCid1());
        goods.setCid2(spuBo.getCid2());
        goods.setCid3(spuBo.getCid3());
        goods.setBrandId(spuBo.getBrandId());
        goods.setCreateTime(spuBo.getCreateTime());
        goods.setSubTitle(spuBo.getSubTitle());
        goods.setAll(spuBo.getTitle()+" "+brand.getName()+" "+ org.apache.commons.lang3.StringUtils.join(categoryNameList," "));
        goods.setPrice(prices);
        goods.setSkus(MAPPER.writeValueAsString(skuMapList)); //需要把刚刚封装的Map集合转成JSON
        goods.setSpecs(paramMap);


        return goods;
    }





    public String choseSegment(String value,SpecParam p ){
        double val = NumberUtils.toDouble(value);
        String result = "其他";

        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            //获取取值范围
            double begin =  NumberUtils.toDouble(segs[0]) ;
            double end = Double.MAX_VALUE ;
            if(segs.length ==2){
                end  = NumberUtils.toDouble(segs[1]) ;
            }

            //判断是否在范围
            if (val >= begin && val < end ){
                if (segs.length == 1){
                    result = segs[0]+p.getUnit()+"以上";
                }else if (begin == 0){
                    result = segs[1]+p.getUnit()+"以下";
                }else {
                    result  = segment + p.getUnit();
                }
                break;
            }
        }




        return result;
    }
}
